import React from 'react';
import { Form, Divider, Button, Icon, Row, message, Modal, Spin } from 'antd';
import { history } from 'umi'
import { useRequest, defaultFormatResult } from '@/hooks';
import { getCandidateInfo, updateCandidateInfo } from '@/pages/Recruitment/Hire/service';
import { primaryColor } from '@/defaultSettings';
import { TitleControl } from '@/pages/Recruitment/components';

import { ContactItem, Salary } from './containers';
import { PageWrap } from './components';

const styleTitle = title => (
    <div style={{ fontWeight: 'bold', fontSize: 14, marginLeft: -7 }}>
        <Divider type="vertical" style={{ width: 4, background: primaryColor }} /> {title}
    </div>
);

const contactPersonStyle = {
    height: 43,
    background: '#F6F7F8',
    borderRadius: 4,
    border: '1px solid #E8EAEF',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '0 14px',
    marginBottom: 8
};

const titleProps = {
    titleRender: styleTitle,
    showButton: false
};

const oneLineLayout = {};

const renderItem = (EditComponent, ViewComponent, editFlag = true) => (editFlag ? EditComponent : ViewComponent);

const ID_PREFIX = 'NEW_';

const editLayout = {
    layout: 'vertical',
    wrapperCol: { span: 18 }
};

const viewLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 14 }
};

const Candidate = ({ location, form }) => {
    const { query } = location;
    const { signCandidateId } = query;

    // 候选人信息
    const { loading, data: talentInfo = {} } = useRequest(() => getCandidateInfo(signCandidateId), {
        refreshDeps: [signCandidateId],
        ...defaultFormatResult
    });

    // 保存候选人信息
    const { loading: submitLoading, run: runSubmit } = useRequest(updateCandidateInfo, {
        manual: true,
        ...defaultFormatResult
    });

    // 联系人
    const [contacts, setContacts] = React.useState([]);

    const hasWorkExp = talentInfo?.recruitTalentBackgroundSalary?.talentWorkType === 1;

    React.useEffect(() => {
        if (!hasWorkExp) return;
        if (talentInfo?.recruitTalentBackgrounds?.length) {
            setContacts(talentInfo?.recruitTalentBackgrounds?.map(item => ({ id: item.id })));
        } else {
            setContacts([{ id: `${ID_PREFIX}0` }]);
        }
        if (talentInfo?.backgroundFlag === 1) {
            message.info('您已提交过相关信息！');
        }
    }, [talentInfo]);

    const isEdit = talentInfo?.backgroundFlag !== 1;
    // const isEdit = true;

    const formItemLayout = isEdit ? editLayout : viewLayout;

    const commonProps = {
        form,
        talentInfo,
        oneLineLayout,
        renderItem,
        isEdit
    };

    const generateId = () => {
        if (!contacts.length) return 0;
        const nextId = Math.max(...contacts.map(item => Number(String(item.id).replace(ID_PREFIX, '')))) + 1;
        return ID_PREFIX + nextId;
    };

    const handleAdd = () => {
        setContacts([...contacts, { id: generateId() }]);
    };

    const handleRemove = id => {
        // 需要标记删除服务端
        if (talentInfo?.recruitTalentBackgrounds?.some(item => item.id === id)) {
            setContacts(
                contacts.map(item => {
                    if (id === item.id) {
                        return { ...item, delete: true };
                    }
                    return item;
                })
            );
        } else {
            setContacts(contacts.filter(item => item.id !== id));
        }
    };

    const handleSubmit = () => {
        const callSubmit = values => {
            Modal.confirm({
                title: '确定要提交吗',
                // content: '提交后无法二次修改',
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    const { recruitTalentBackgroundSalary = {}, recruitTalentBackgrounds = [] } = values;
                    const { salaryProveRelationsFileList, ...rest } = recruitTalentBackgroundSalary;
                    const postParams = {
                        employId: talentInfo.employId,
                        recruitTalentBackgroundSalary: {
                            ...rest
                        },
                        recruitTalentBackgrounds: contacts.map(item => {
                            if (item.delete) {
                                return {
                                    id: item.id,
                                    operationType: 2
                                };
                            }
                            const bgData = recruitTalentBackgrounds[item.id];
                            const insertUpdateProps = String(item.id).includes(ID_PREFIX)
                                ? { operationType: 0 }
                                : { operationType: 1, id: item.id };

                            return {
                                ...bgData,
                                ...insertUpdateProps,
                                backgroundTime: bgData.backgroundTime.format('YYYY-MM-DD HH:mm:ss')
                            };
                        })
                    };
                    const result = await runSubmit(postParams);
                    if (result) {
                        message.success('提交成功');
                        setTimeout(() => {
                            history.go(0);
                        }, 2000);
                    }
                },
                onCancel() {
                    console.log('Cancel');
                }
            });
        };

        form.validateFieldsAndScroll((errors, values) => {
            if (errors) return;
            callSubmit(values);
        });
    };

    const getContactDetail = id => talentInfo?.recruitTalentBackgrounds?.find(item => item.id === id);

    const bannerText = (
        <>
            <div>
                欢迎应聘 <strong>{talentInfo?.recruitTalentBackgroundSalary?.companyName}</strong>
            </div>
            <div>请提供薪资及背调联系人信息</div>
        </>
    );

    return (
        <PageWrap bannerText={bannerText}>
            <Spin spinning={loading}>
                <div style={{ fontSize: 18 }}>
                    <strong>应聘职位：{talentInfo?.recruitTalentBackgroundSalary?.dutyName}</strong>
                </div>
                <Form {...formItemLayout}>
                    <TitleControl title="薪资福利" {...titleProps}>
                        <Salary {...commonProps} />
                    </TitleControl>
                    {hasWorkExp && (
                        <TitleControl title="背调联系人信息" {...titleProps}>
                            <p>
                                <strong style={{ paddingLeft: 10 }}>
                                    建议提供3个联系人信息，上级主管、同级同事、下属同事（若有）各1个
                                </strong>
                            </p>
                            {contacts
                                .filter(item => !item.delete)
                                .map((item, index) => (
                                    <div key={item.id}>
                                        <div style={contactPersonStyle}>
                                            <strong>联系人 {index + 1}</strong>
                                            {index > 0 && isEdit && (
                                                <Icon
                                                    type="close-circle"
                                                    theme="filled"
                                                    onClick={() => {
                                                        handleRemove(item.id);
                                                    }}
                                                />
                                            )}
                                        </div>
                                        <ContactItem
                                            {...commonProps}
                                            workCompanyList={talentInfo?.workCompanyList}
                                            id={item.id}
                                            detail={getContactDetail(item.id)}
                                        />
                                        <Divider style={{ backgroundColor: '#ededed' }} />
                                    </div>
                                ))}
                            {isEdit && (
                                <Button
                                    style={{
                                        width: '100%',
                                        background: 'rgba(0, 0, 0, 0.05)',
                                        height: 43,
                                        border: 'none'
                                    }}
                                    onClick={handleAdd}
                                >
                                    <Icon type="plus" />
                                    添加
                                </Button>
                            )}
                        </TitleControl>
                    )}
                </Form>
                {isEdit && (
                    <Row type="flex" justify="center">
                        <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                            提交
                        </Button>
                    </Row>
                )}
            </Spin>
        </PageWrap>
    );
};

export default Form.create()(Candidate);
